<?php
/**
 * Provides methods to interact with reports
 *
 * @author Alejandro Quintero <yasakani@gmail.com>
 * @name report
 * @version 0.1
 * @package Collabtive
 * @link http://www.o-dyn.de
 * @license http://opensource.org/licenses/gpl-license.php GNU General Public License v3 or laterg
 */
class report {
	
    public $mylog;
    
    // Flags to show corresponding elements data in report array
    var $show_companies;
    var $show_milestones;
    var $show_tasks;
    var $show_files;

    /**
     * Constructor
     * Initializes event log
     */
    function __construct($show_companies = true, $show_milestones = true, $show_tasks = true, $show_files = true) {
        $this->mylog = new mylog;
        
        // Set flags
        $this->show_companies = $show_companies;
        $this->show_milestones = $show_milestones;
        $this->show_tasks = $show_tasks;
        $this->show_files = $show_files;
        
    }

    /**
     * 
     * @param boolean $company_id
     * @param boolean $date
     * @param boolean $date_end
     */
    public function generate($company_id, $date, $date_end, $project_status = null, $project_id, $milestone_status, $milestone_id, $project_files) {
    	
    	if ( !$project_status ) return array();
    	
		// Project status
		switch ($project_status) {
			
			// All the projects
			case 'all':
				$projects = $this->getAllProjectsFromCompany($company_id);
				break;
			
			// Only finished projects
			case 'finished':
				$projects = $this->getFinishedProjectsFromCompany($company_id);
				break;
			
			// Only pending projects
			case 'pending':
				$projects = $this->getPendingProjectsFromCompany($company_id);
				break;
			
			case 'list':
				$projects = $this->getProject($project_id);
				break;
			
			default:
				$projects = array();
			
		}
		
		// No projects matches with the criteria
		if ( empty($projects) ) return array();
		
		# Only projects on date
		
		// Start date
		$date_ini = strtotime($date);
		
		// End date
		if ( $date_end )
			$date_end = mktime(23, 59, 59, date('m', strtotime($date_end)), date('d', strtotime($date_end)), date('Y', strtotime($date_end)));
		else
			$date_end = mktime(23, 59, 59, date('m', $date_ini), date('d', $date_ini), date('Y', $date_ini));
		
		// Traverse projects for find matches with date interval
		foreach ( $projects as $i => $project ) {
		
			$project_start = $project['start'];
			$in_date = ( $project_start > $date_ini && $project_start < $date_end );
			if ( !$in_date ) unset($projects[$i]);
			
		}
		
		if ( empty($projects) ) return array();
		
		// Strip tags from data, sanitize and format data
		foreach ( $projects as $i => $project ) {
			$projects[$i]['desc'] = strip_tags( $project['desc'] );
		}
		
		# Companies
		
		// "Show companies" is enabled
		if ( $this->show_companies ) {
			
			// Re-arrange data to display
			foreach ($projects as $i => $project) {
				$projects[$i]['companies'] = $this->getAllCompaniesInProyect( $project['ID'] );
			}
			
		}
		
		# Milestones
		
		// "Show milestones" is enabled
		if ( $this->show_milestones ) {
			
			$milestoneObj = new milestone();
			
			// Milestone status
			switch ( $milestone_status ) {
					
				case 'all':
					foreach ( $projects as $i => $project ) {
						$projects[$i]['milestones'] = $milestoneObj->getAllProjectMilestones( $project['ID'] );
					}
					break;
						
				case 'finished';
				foreach ( $projects as $i => $project ) {
					$projects[$i]['milestones'] = $milestoneObj->getDoneProjectMilestones($project['ID']);
				}
				break;
					
				case 'pending':
					foreach ( $projects as $i => $project ) {
						$projects[$i]['milestones'] = $milestoneObj->getProjectMilestones($project['ID']);
					}
					break;
						
				case 'list':
					foreach ( $projects as $i => $project ) {
						$projects[$i]['milestones'] = $milestoneObj->getMilestone($milestone_id);
					}
					break;
						
				default:
					foreach ( $projects as $i => $project ) {
						$projects[$i]['milestones'] = array();
					}
						
			}
			
			// Sanitize data
			foreach ( $projects as $i => $project ) {
				
				// Delete unnecessary data and strip tags
				if ( !empty($project['milestones']) ) {
					foreach ( $project['milestones'] as $j => $milestone ) {
						unset($projects[$i]['milestones'][$j]['tasks']);
						unset($projects[$i]['milestones'][$j]['messages']);
						$projects[$i]['milestones'][$j]['desc'] = strip_tags($milestone['desc']);
					}
				}
				
				// Turn boolean type data to array
				if ( !$project['milestones'] )
					$projects[$i]['milestones'] = array();
				
			}
			
		}
		
		# Tasks
		
		// "Show tasks" is enabled
		if ( $this->show_tasks ) {
			
			$task = new task();
			
			foreach ( $projects as $i => $project ) {
				$projects[$i]['tasks'] = $task->getProjectTasks( $project['ID'] );
			}
			
			// Sanitize data
			foreach ( $projects as $i => $project ) {
				
				// Delete unnecessary data and strip tags
				if ( !empty($project['tasks']) ) {
					foreach ( $project['tasks'] as $j => $task ) {
						unset($projects[$i]['tasks'][$j]['users']);
						$projects[$i]['tasks'][$j]['text'] = strip_tags($task['text']);
					}
				}
				
				// Turn boolean type data to array
				if ( !$project['tasks'] )
					$projects[$i]['tasks'] = array();
				
			}
			
		}
		
		# Files
		
		// "Show files" is enabled
		if ( $this->show_files ) {
			
			if ( $project_files ) {
					
				$file = new datei();
					
				foreach ($projects as $i => $project) {
					$projects[$i]['files'] = $file->getAllProjectFiles($project['ID']);
				}
				
				// Sanitize data
				foreach ( $projects as $i => $project ) {
					
					// Delete unnecessary data
					if ( !empty($project['files']) ) {
						foreach ( $project['files'] as $j => $file ) {
							$projects[$i]['files'][$j]['username'] = $file['userdata']['name'];
							unset($projects[$i]['files'][$j]['userdata']);
						}
					}
						
					// Turn boolean type data to array
					if ( !isset($project['files']) || !$project['files'] )
						$projects[$i]['files'] = array();
						
				}
				
			}
			
		}
		
		return $projects;
		
    }
    
    public function save($name = null, $criteria = array(), $report = array()) {
    	
    	if ( empty($criteria) || empty($report) || !$name ) return false;
    	
    	// Serialize data for criteria to store on database
    	$criteria = serialize($criteria);
    	
    	// Serialize data for all the report information to store on database
    	$report = serialize($report);
    	
    	$query = "INSERT INTO reports (ID, name, date, criteria, report) 
    	VALUES (NULL, '$name', NOW(), '$criteria', '$report');";
    	
    	$result = mysql_query($query);
    	
    	if ( !$result ) return false;
    	else {
    		$last_insert_id = mysql_insert_id();
    		return $last_insert_id;
    	}
    	
    }
    
    public function delete( $report_id = null ) {
    	
    	if ( !$report_id ) return false;
    	
    	$report_id = (int) mysql_real_escape_string( $report_id );
    	
    	$query = "DELETE FROM reports WHERE ID = $report_id;";
    	$result = mysql_query( $query );
    	
    	if ( $result ) return true;
    	else return false;
    	
    }
    
    /**
     * 
     * @param int $report_id
     * @return boolean|multitype:
     */
    public function getReport($report_id = null) {
    	
    	if ( !$report_id ) return false;
    	
    	$report_id = (int) mysql_real_escape_string($report_id);
    	
    	$query = "SELECT * FROM reports WHERE ID = $report_id LIMIT 0,1;";
    	$result = mysql_query($query);
    	
    	$report = mysql_fetch_assoc($result);
    	
    	if ( empty($report) ) return array();
		
    	// Unserialize stored data
    	$report['criteria'] = unserialize( $report['criteria'] );
    	$report['report'] = unserialize( $report['report'] );
		
    	return $report;
    	
    }
    
    /**
     * Get all reports from database
     * @return array Return an array of the all reports data
     */
    public function getAllReports() {
    	
    	$query = "SELECT ID FROM reports;";
    	$result = mysql_query($query);
    	
    	$reports = array();
    	
    	while ( $report = mysql_fetch_assoc($result) ) {
    		$reports[] = $this->getReport( $report['ID'] );
    	}
    	
    	if ( empty($reports) ) return array();
    	
    	return $reports;
    	
    }
    
    /**
     * Get all the projects and its data from a company
     * @param integer $company_id Company ID.
     */
	public function getAllProjectsFromCompany($company_id = null) {
		
		$company_id = (int) mysql_real_escape_string($company_id);
		
		$query_where = ( !$company_id ) ? '' : "WHERE company = $company_id";
		$query = "SELECT user FROM company_assigned $query_where;";
		$result = mysql_query($query);
		
		$users = array();
		
		while ( $user = mysql_fetch_assoc($result) ) {
			$users[] = $user['user'];
		}
		
		# Get all projects where users are involved
		
		if ( empty($users) ) return array();
		
		$users_ids = join(',', $users);
		
		$query = "SELECT projekt FROM projekte_assigned WHERE user IN ($users_ids) GROUP BY projekt;";
		$result = mysql_query($query);
		
		$project = new project();
		$projects = array();
		
		while ($project_id = mysql_fetch_assoc($result) ) {
			$projects[] = $project->getProject( $project_id['projekt'] );
		}
		
		return $projects;
		
	}
	
	/**
	 * Gets finished projects of the company specified
	 * @param integer $company_id Company identifier
	 */
	public function getFinishedProjectsFromCompany($company_id = null) {
		
		$company_id = (int) mysql_real_escape_string($company_id);
		
		$projects = $this->getAllProjectsFromCompany($company_id);
		
		if ( empty($projects) ) return array();
		
		// Only finished projects, status = 0;
		foreach ($projects as $i => $project) {
			if ( (int) $project['status'] == 1 ) unset($projects[$i]);
		}
		
		return $projects;
		
	}
	
	/**
	 * Gets pending projects of the company specified
	 * @param integer $company_id Company identifier
	 */
	public function getPendingProjectsFromCompany($company_id = null) {
		
		$company_id = (int) mysql_real_escape_string($company_id);
		
		$projects = $this->getAllProjectsFromCompany($company_id);
		
		if ( empty($projects) ) return array();
		
		// Only pending projects, status = 1;
		foreach ($projects as $i => $project) {
			if ( (int) $project['status'] == 0 ) unset($projects[$i]);
		}
		
		return $projects;
		
	}
	
	/**
	 * Gets data of the specified project
	 * @param integer $project_id Project identifier
	 */
	public function getProject($project_id = null) {
		
		if ( !$project_id ) return false;
		
		$project_id = (int) $project_id;
		
		$projects = $this->getAllProjectsFromCompany();
		
		if ( empty($projects) ) return array();
		
		$project_data = array();
		
		foreach ( $projects as $i => $project ) {
			if ( (int) $project['ID'] == $project_id ) $project_data[] = $projects[$i];
		}
		
		return $project_data;
		
	}
	
	/**
	 * 
	 * @param integer $project_id
	 */
	public function getAllCompaniesInProyect($project_id = null) {
		
		if ( !$project_id ) return false;
		
		$query = "SELECT user FROM projekte_assigned WHERE projekt = $project_id ";
		$result = mysql_query($query);
		
		$users = array();
		
		while ($user = mysql_fetch_assoc($result)) {
			$users[] = $user['user'];
		}
		
		if ( empty($users) ) return array();
		
		$users_ids = join(',', $users);
		
		$query = "SELECT company FROM company_assigned WHERE user IN ($users_ids) GROUP BY company;";
		$result = mysql_query($query);
		
		$company = new company();
		$companies = array();
		
		while ($company_id = mysql_fetch_assoc($result) ) {
			$companies[] = $company->getProfile( $company_id['company'] );
		}
		
		unset($company);
		
		return $companies;
		
	}
	
}